package logic

import (
	"gameserver/entitydef"
	"gameserver/server"

	"gitee.com/night-tc/gobige/dbmanager"
	"gitee.com/night-tc/gobige/entity"
	"gitee.com/night-tc/gobige/entity/props"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/logger"
	"gitee.com/night-tc/gobige/timerwheel"
)

/* 玩家逻辑 */

type Player struct {
	/* 对象属性 */
	entity.Entity
	entitydef.NttPlayerByGameDef
	entity.DelayCallHost

	/* 数据库数据 */
	*dbmanager.DBPlayer
	*dbmanager.ModuleBase

	// 定时器
	Timer *timerwheel.Timer
}

// Gateway通知的玩家断线重连
func (this *Player) ReLoadPlayer(state uint32) {
	if state == 1 {
		// 客户端没数据，需要全量同步
		this.DBPlayer.AllDataSync()
		this.DBPlayer.AllDelayDataSync()
	} else {
		// 断线重连 不进行全量同步
	}
}

//---------------------------------------------------------------------
/* IEntity 接口实现 */

func (this *Player) OnCreated(etype string, eid, dbid uint64, realPtr entity.IEntity, spacePtr entity.IEntities, fly bool, param ...interface{}) error {
	if err := this.Entity.OnCreated(etype, eid, dbid, realPtr, spacePtr, fly, param...); err != nil {
		return err
	}
	if err := this.Init(); err != nil {
		return err
	}
	return nil
}

// 初始化
func (this *Player) Init() error {
	logger.Debugf(server.LogKey_LoginFlow, "Player Init eid:%d", this.GetEntityID())
	if err := this.Entity.Init(); err != nil {
		return err
	}
	this.Timer = timerwheel.NewTimer()
	this.Timer.Start()
	this.ModuleBase = dbmanager.NewModuleBase(this, "Player")
	this.ModuleBase.LoadType = global.ServerTypeDB
	this.SetSorter(props.EDPSorterTypeSave, dbmanager.NewPropsDirtySave(this, this.ModuleBase.Args))
	this.RegMsgProc(&GatewayProc{this})
	this.DBPlayer = dbmanager.NewDBPlayer(this, global.GetCfgInst().GetServerID(), this.dataLoaded)
	this.DBPlayer.Init(nil)
	return nil
}

// 循环调用中
func (this *Player) Looping() {
	this.Timer.OnTick(this.GetNowTime())
	this.Entity.Looping()
}

func (this *Player) Looped() {
	this.Exec()
	this.Entity.Looped()
	this.DBPlayer.Save()
}
func (this *Player) Destroy() {
	this.Entity.Destroy()
	this.Timer.DeleteAllTimerTask()
}

/* IEntity 接口实现 */
//-------------------------------------------------------------------------
/* 私有函数 */

func (this *Player) dataLoaded() {

}
